package com.hzp.micromall.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzp.micromall.admin.dto.UmsAdminDto;
import com.hzp.micromall.admin.dto.UpdateAdminPasswordParam;
import com.hzp.micromall.admin.entity.UmsRole;
import com.hzp.micromall.admin.service.UmsMenuService;
import com.hzp.micromall.common.core.api.CommonPage;
import com.hzp.micromall.common.core.api.CommonResult;
import com.hzp.micromall.common.core.api.ResultCode;
import com.hzp.micromall.admin.dto.UmsAdminParam;
import com.hzp.micromall.admin.entity.UmsAdmin;
import com.hzp.micromall.admin.dto.UmsAdminLoginParams;
import com.hzp.micromall.admin.service.UmsAdminService;
import com.hzp.micromall.common.core.entity.UserDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author houzipeng
 * @Date 2022/2/16 23:38
 * @Version 1.0
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/admin")
@Slf4j
public class UmsAdminController {
    @Autowired
    private UmsAdminService adminService;

    @Autowired
    private UmsMenuService menuService;

    @ApiOperation(value = "用户注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<UmsAdmin> register(@Validated @RequestBody UmsAdminParam umsAdminParam) {
        log.info("用户注册 请求参数：{}", JSONUtil.parse(umsAdminParam));
        UmsAdmin umsAdmin = adminService.register(umsAdminParam);
        if (umsAdmin == null) {
            return CommonResult.failed(ResultCode.USER_ACCOUNT_ALREADY_EXISTS);
        }
        return CommonResult.success(umsAdmin);
    }

    @ApiOperation(value = "登录以后返回token")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@Validated @RequestBody UmsAdminLoginParams umsAdminLoginParams) {
        log.info("用户登录 请求参数：{}", JSONUtil.toJsonStr(umsAdminLoginParams));
        return adminService.login(umsAdminLoginParams.getUsername(),umsAdminLoginParams.getPassword());
    }

    @ApiOperation(value = "登出功能")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult logout() {
        log.info("用户注销");
        return CommonResult.success(null);
    }

    @ApiOperation("根据用户名获取通用用户信息")
    @RequestMapping(value = "/loadAdminByUsername", method = RequestMethod.GET)
    @ResponseBody
    public UserDto loadUserByUsername(@RequestParam String username) {
        log.info("根据用户名获取通用用户信息 请求参数：{}", username);
        UserDto userDto = adminService.loadUserByUsername(username);
        return userDto;
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getAdminInfo() {
        log.info("获取当前登录用户信息");
        UmsAdmin umsAdmin = adminService.getCurrentAdmin();
        Map<String, Object> data = new HashMap<>();
        data.put("username", umsAdmin.getUsername());
        data.put("menus", adminService.getMenuList(umsAdmin.getId()));
        data.put("icon", umsAdmin.getIcon());
        List<UmsRole> roleList = adminService.getRoleList(umsAdmin.getId());
        if(CollUtil.isNotEmpty(roleList)){
            List<String> roles = roleList.stream().map(UmsRole::getName).collect(Collectors.toList());
            data.put("roles",roles);
        }
        return CommonResult.success(data);
    }

    @ApiOperation("根据用户名或姓名分页获取用户列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<UmsAdminDto>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                      @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        log.info("根据用户名或姓名分页获取用户列表 请求参数：[{}]",keyword, pageSize, pageNum);
        CommonPage<UmsAdminDto> page = adminService.page(keyword, pageSize, pageNum);
        return CommonResult.success(page);
    }

    @ApiOperation("根据用户Id获取指定用户信息")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<UmsAdmin> getItem(@PathVariable Long id) {
        log.info("根据用户Id获取指定用户信息 请求参数：{}", id);
        UmsAdmin admin = adminService.getAdminById(id);
        return CommonResult.success(admin);
    }

    @ApiOperation("根据用户Id获取指定用户的角色")
    @RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<UmsRole>> getRoleList(@PathVariable Long adminId) {
        log.info("根据用户Id获取指定用户的角色 请求参数：{}", adminId);
        List<UmsRole> roleList = adminService.getRoleList(adminId);
        return CommonResult.success(roleList);
    }

    @ApiOperation("修改指定用户信息")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@PathVariable Long id, @RequestBody UmsAdmin admin) {
        log.info("修改指定用户信息 请求参数：[{}]", id, JSONUtil.toJsonStr(admin));
        int count = adminService.updateAdminById(id, admin);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("修改指定用户密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updatePassword(@RequestBody UpdateAdminPasswordParam updatePasswordParam) {
        log.info("修改指定用户密码 请求参数：{}", JSONUtil.toJsonStr(updatePasswordParam));
        ResultCode result = adminService.updatePassword(updatePasswordParam);
        return result.getCode().equals(200) ? CommonResult.success() : CommonResult.failed(result);
    }

    @ApiOperation("删除指定用户信息")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@PathVariable Long id) {
        log.info("删除指定用户信息 请求参数：{}", id);
        int count = adminService.deleteAdminById(id);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("修改帐号状态")
    @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateStatus(@PathVariable Long id,@RequestParam(value = "status") Integer status) {
        log.info("修改帐号状态 请求参数 用户Id：{} 修改后状态：{}", id, status);
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setStatus(status);
        int count = adminService.updateAdminById(id,umsAdmin);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("给用户分配角色")
    @RequestMapping(value = "/role/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateRole(@RequestParam("adminId") Long adminId,
                                   @RequestParam("roleIds") List<Long> roleIds) {
        log.info("给用户分配角色 请求参数 用户Id：{} 角色Ids：{}", adminId, JSONUtil.toJsonStr(roleIds));
        int count = adminService.updateAdminRoleRelation(adminId, roleIds);
        if (count >= 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }
}
